package com.sf.osms.dep.processor.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * AES加密工具类 
 *
 */
public class AesUtil {
    
    public static final String AESKEY = "2D2FF77D67ECD398";
	
    /**
     * AES加密
     * @param sSrc 明文
     * @param sKey 密钥
     * @return
     * @throws Exception
     */
    public static String encrypt(String sSrc)
    {      
        try
        {
            byte[] raw = AESKEY.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            
            // 算法/模式/补码方式
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            
            // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            IvParameterSpec iv = new IvParameterSpec(AESKEY.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes());
      
            // 此处使用BAES64做转码功能，同时能起到2次加密的作用
            return new BASE64Encoder().encode(encrypted);
            
        }
        catch(Exception e)
        {
            System.out.println(e.toString());
        }
        
        return null;
    }  
  
    /**
     * AES解密  
     * @param sSrc 密文
     * @param sKey 密钥
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc)
    {
        try 
        {
            byte[] raw = AESKEY.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(AESKEY.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            
            // 先用BASE64解密
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);
            try
            {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original);
                return originalString;
            }
            catch (Exception e)
            {
                System.out.println(e.toString());
                return null;
            }
        }
        catch (Exception ex)
        {
            System.out.println(ex.toString());
            return null;
        }
    }

}
